<template>
  <div id="empty">

    <div class="top">
      <span class="title" style="margin-top: 3vh">当前就诊</span>
      <div class="box">
        <div ref="con1" :class="{anim:animateCurrent==true}">
          <div v-for='(item, index) in currentList' :key="index">
            <div class="item">{{item.name}}（{{getDepartment(item.doctorId)}}）</div>
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="title">等待就诊</div>
      <div class="box">
        <div ref="con2" :class="{anim:animateWait==true}">
          <div v-for='(item, index) in waitList' :key="index" class="item">
            <div style="position:relative;"><span style="margin-left: 7vh">{{item.id}}.</span><span>{{item.name}}{{item.state, item.isAppointment | filStatus}}</span></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "empty",
  data() {
    return {
      animateCurrent: false,
      currentList: [],
      animateWait: false,
      waitList: [],
      doctorList: [],
      socket: null,
      socketAccount: 'electronicScreen',
    }
  },
  created() {
    this.getData()
    this.timer1 = setInterval(this.scroll1, 2000)
    this.timer2 = setInterval(this.scroll2, 2000)
  },
  mounted() {
    this.openSocket()
  },
  beforeDestroy() {
    this.closeSocket()
  },
  destroyed() {
    this.closeSocket()
  },
  methods: {
    getData() {
      let _this = this
      let result = []
      this.currentList = []
      this.waitList = []
      this.$axios.get('https://mp.wwtsz.com:8811/allDoctor').then(res => {
        _this.doctorList = res.data.result
      })
      this.$axios.get('https://mp.wwtsz.com:8812/manager/electronicScreen').then(res => {
        console.log(res)
        result = res.data.result
        let passList = []
        for (let i = 0; i < result.length; i++) {
          let item = result[i]
          if (item.state === 1) {
            _this.waitList.push(item)
          }
          if (item.state === 2) {
            _this.currentList.push(item)
          }
          if (item.state === 4) {
            passList.push(item)
          }
        }
        this.waitList.sort(down)
        this.waitList.push.apply(this.waitList, passList)
        for (let j = 0; j < _this.waitList.length; j++) {
          _this.waitList[j].id = j + 1
        }
      })
      function down(x,y) {
        return y.isAppointment - x.isAppointment
      }
    },
    getDepartment(doctorId) {
      let _this = this
      for (let i = 0; i < _this.doctorList.length; i++) {
        if (doctorId === _this.doctorList[i].id) {
          return _this.doctorList[i].department
        }
      }
    },
    scroll1 () {
      if (this.currentList.length > 1) {
        let con1 = this.$refs.con1
        con1.style.marginTop = '-8vh'
        this.animateCurrent = !this.animateCurrent
        setTimeout(() => {
          this.currentList.push(this.currentList[0])
          this.currentList.shift()
          con1.style.marginTop = '0vh'
          this.animateCurrent = !this.animateCurrent
        }, 1000)
      }

    },
    scroll2 () {
      if (this.waitList.length > 6) {
        let con2 = this.$refs.con2
        con2.style.marginTop = '-21.5vh'
        this.animateWait = !this.animateWait
        setTimeout(() => {
          this.waitList.push(this.waitList[0])
          this.waitList.push(this.waitList[1])
          this.waitList.push(this.waitList[2])
          this.waitList.shift()
          this.waitList.shift()
          this.waitList.shift()
          con2.style.marginTop = '0vh'
          this.animateWait = !this.animateWait
        }, 1000)
      }
    },
    openSocket: function () {
      let _this = this
      let socketUrl="https://mp.wwtsz.com:8813/ws/" + this.socketAccount;
      socketUrl = socketUrl.replace("https","wss").replace("http","ws");

      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }else{
        console.log("您的浏览器支持WebSocket");
        var lockReconnect = false;//避免重复连接
        var ws;
        var tt;
        //创建链接
        createWebSocket();
        //创建链接
        function createWebSocket() {
          try {
            ws = new WebSocket(socketUrl);
            // 初始化链接
            init();
          } catch(e) {
            console.log('catch'+e);
            reconnect(socketUrl);
          }
        }

        /**
         * 初始化链接
         */
        function init() {
          ws.onclose = function () {
            reconnect(socketUrl);
          };
          ws.onerror = function() {
            reconnect(socketUrl);
          };
          ws.onopen = function () {
            ws.send("连接成功");
            //心跳检测重置
            heartCheck.start();
          };
          ws.onmessage = function (event) {
            heartCheck.start();
            //拿到任何消息都说明当前连接是正常的
            //实时添加消息
            if (_this.isJson(event.data)) {
              _this.getData()
              setTimeout(() => {
                let data = JSON.parse(event.data)
                if (data.contentText === 'update') {
                  for (let i = 0; i < _this.currentList.length; i++) {
                    var item = _this.currentList[i];
                    if (item.number === data.number) {
                      let name = item.name
                      // _this.speckText("请" + item.name + "到101室就诊")
                      _this.$axios.get('https://mp.wwtsz.com:8812/manager/doctor/check?doctorId=' + item.doctorId)
                          .then(res => {
                            _this.speckText("请" + name + "到" + res.data.result.department + "就诊")
                          })
                    }
                  }
                }
              },1000)

            }
          }
        }

        var lockReconnect = false;//避免重复连接
        //重试连接socket
        function reconnect(wsUrl) {
          if(lockReconnect) {
            return;
          };
          lockReconnect = true;
          //没连接上会一直重连，设置延迟避免请求过多
          tt && clearTimeout(tt);
          tt = setTimeout(function () {
            createWebSocket(wsUrl);
            lockReconnect = false;
          }, 180000);
        }
        //心跳检测
        var heartCheck = {
          timeout: 30000,
          timeoutObj: null,
          serverTimeoutObj: null,
          start: function(){
            var self = this;
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function(){
              //这里发送一个心跳，后端收到后，返回一个心跳消息，
              //onmessage拿到返回的心跳就说明连接正常
              ws.send("连接成功");
              self.serverTimeoutObj = setTimeout(function() {
                console.log(ws);
                ws.close();
              }, self.timeout);
            }, this.timeout)
          }
        }
      }
    },
    closeSocket: function() {
      this.socket.close()
    },
    isJson: function (str) {
      if (typeof str == 'string') {
        try {
          let obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            return false;
          }

        } catch (e) {
          // console.log('error：'+str+'!!!'+e);
          return false;
        }
      }
      console.log('It is not a string!')
    },
    speckText(str) {
      let utterance = new SpeechSynthesisUtterance();
      utterance.text = str;
      utterance.lang = 'zh';
      utterance.rate = 0.6;
      speechSynthesis.speak(utterance)
    },
  },
  // watch: {
  //   currentList(value) {
  //     if (value.length > 1) {
  //       setInterval(this.scroll1, 2000)
  //     }
  //   },
  //   waitList(value) {
  //     if (value.length > 5) {
  //       setInterval(this.scroll1, 2000)
  //     }
  //   }
  // },
  filters: {
    filStatus(value, status) {
      if (value === 4) {
        return '(过)'
      }
      if (status === 1) {
        return '(预)'
      }
    }
  }
}
</script>

<style scoped>
#empty{
  position: absolute;
  width: 100%;
  height: 100%;
  margin-top: 3%;
}
.top {
  position: relative;
  width: 90%;
  min-height: 20%;
  /*background-color: #333;*/
  margin: 0 auto;
  background: url("../../static/bg.png") no-repeat;
  background-size: cover;
  margin-bottom: 3vh;
  border-radius: 1.5vh;
  box-shadow: 0px 0px 3vh rgba(0,0,0,.2);
}
.top .box {
  clear: left;
  position: absolute;
  top: 7vh;
  left: 32vh;
  height: 8vh;
  width: 80%;
  overflow: hidden;
}
.top .box .item {
  text-align: left;
  margin-left: 10vh;
  width: 100%;
  font-size: 7vh;
  font-weight: bold;
  /*margin-bottom: 2.5vh;*/
}
.content {
  position: relative;
  width: 90%;
  min-height: 65%;
  /*background-color: #333;*/
  margin: 0 auto;
  background: url("../../static/bg.png") no-repeat;
  background-size: cover;
  border-radius: 1.5vh;
  box-shadow: 0px 0px 3vh rgba(0,0,0,.2);
}
.content .box {
  clear: left;
  height: 45vh;
  width: 100%;
  overflow: hidden;
}
/*.content .box .item:first-child{*/
/*  width: 30%;*/
/*}*/
.content .box .item {
  text-align: left;
  float: left;
  width: 33%;
  font-size: 8vh;
  line-height: 18vh;
  margin-top: 1.5vh;
  margin-bottom: 2vh;
  font-weight: bold;
}
.title{
  float: left;
  font-size: 8vh;
  font-weight: bold;
  padding: 3vh;
  margin-left: 3vh;
  color: #986923;
}
.item .state {
  background-color: #c9a46d;width: 30vh;padding: 0.5vh;display: block;margin: 0 auto;color: #333;
}
.anim{
  transition: all .8s;
}
</style>